package org.kjtc.security;

import java.util.HashSet;
import java.util.Set;

import javax.annotation.Resource;

import org.kjtc.entity.Role;
import org.kjtc.entity.User;
import org.kjtc.entity.UserRole;
import org.kjtc.service.RoleService;
import org.kjtc.service.UserService;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityMessageSource;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service("myUserDetailService")
public class MyUserDetailService implements UserDetailsService {

	@Resource(name = "userService")
	private UserService userService;

	@Resource(name = "roleService")
	private RoleService roleService;
	protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();

	@Override
	public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {

		User users = null;
		User user = new User();

		if (userName != null && !userName.isEmpty()) {
			user.setUserID(userName);
			try {
				users = userService.getUser(user);
			} catch (Exception e) {
				e.printStackTrace();
			}

			if (users != null) {
				Set<GrantedAuthority> grantedAuths = obtionGrantedAuthorities(users);
				if (grantedAuths != null) {
					users.setAuthorities(grantedAuths);
				} else {
					throw new UsernameNotFoundException("用户角色已被禁用，请联系管理员！");
				}
			} else {
				throw new UsernameNotFoundException("用户名或密码错误");
			}
		}

		return users;
	}

	private Set<GrantedAuthority> obtionGrantedAuthorities(User user) {

		Set<GrantedAuthority> grantedAuthorities = new HashSet<GrantedAuthority>();
		Role role = null;
		UserRole userRole = new UserRole();
		userRole.setUserID(user.getUserID());
		try {
			role = roleService.getRoleInfo(userRole);
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (role == null) {
			grantedAuthorities = null;
		} else {
			grantedAuthorities.add(new SimpleGrantedAuthority(role.getRoleID()));
		}

		return grantedAuthorities;
	}
}